/*
 * @Author       : borfish
 * @Date         : 2025-08-07 16:46:00
 * @LastEditors  : borfish
 * @LastEditTime : 2025-08-11 17:01:57
 * @FilePath     : /include/MqttHandler.h
 * @Description  : 
 * Copyright 2025 OBKoro1, All Rights Reserved. 
 * 2025-08-07 16:46:00
 */

 #ifndef MQTTHANDLER_H
 #define MQTTHANDLER_H

 #include <QObject>
 #include <qmqttclient.h>
 #include <qmqttsubscription.h>

 class MQTTHandler : public QObject
 {
    Q_OBJECT

public:
    explicit MQTTHandler(QObject *parent = nullptr);

    // MQTT操作接口
    void connectToBroker(const QString &host, quint16 port,
                        const QString &username = "", const QString &password = "");
    void disconnectFromBroker();
    void publish(const QString &topic, const QString &message,quint8 qos = 0);
    void subscribe(const QString &topic, quint8 qos = 0);
    void unsubscribe(const QString &topic);

    // 状态查询
    bool isConnected() const;
    QMqttClient::ClientState connectionState() const;

signals: 
    // 状态信号
    void connected();
    void disconnected();
    void connectionError(const QString &error);

    // 消息信号
    void messageReceived(const QString &topic,const QString &message);
    void messagePublished(const QString &topic, const QString &message);
    void subscribed(const QString &topic);
    void unsubscribed(const QString &topic);

    // 日志信号
    void logMessage(const QString &message);


private slots:

    void onConnected();
    void onDisconnected();
    void onError(QMqttClient::ClientError error);
    void onMessageReceived(const QByteArray &message, const QMqttTopicName &topic);
    
private:
    QMqttClient *m_client_;
    QString m_lastError_;
 };

 #endif
